﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCA.Community.DAL.Interfaces;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.IO;
using LCA.Community.DAL.Model;

namespace LCA.Community.Cloud.Services
{
    public class StorageServiceContext<T> : IStorageServiceContext<T> where T : BasicStorageModel
    {
        private CloudBlobClient _blobClient;
        private Uri _baseURL;

        public StorageServiceContext()
        {
            var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
            _blobClient = storageAccount.CreateCloudBlobClient();
            _baseURL = _blobClient.BaseUri;
        }

        public void Add(T entity)
        {
            var blob = GetBlobReference(entity);
            blob.UploadFromStream(entity.Stream);
            blob.Properties.ContentType = entity.ContentType;
            blob.SetProperties();
        }

        public void Delete(T entity)
        {
            var blob = GetBlobReference(entity);

            blob.DeleteIfExists();
        }

        public Uri GetUrl(T entity)
        {
            var blob = GetBlobReference(entity);

            return blob.Uri;
        }

        public bool Exist(T entity)
        {
            var blob = GetBlobReference(entity);

            try
            {
                blob.FetchAttributes();
            }
            catch (StorageClientException e)
            {
                if (e.ErrorCode == StorageErrorCode.ResourceNotFound)
                {
                    return false;
                }
                else
                {
                    throw;
                }
            }

            return true;
        }

        public CloudBlobContainer GetContainer(T entity)
        {
            var container = _blobClient.GetContainerReference(entity.Container);

            if (container.CreateIfNotExist())
            {
                var permissions = new BlobContainerPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                container.SetPermissions(permissions);
            }

            return container;
        }

        public CloudBlob GetBlobReference(T entity)
        {
            var container = GetContainer(entity);
            return container.GetBlobReference(entity.Name);
        }

        public Uri BaseURL 
        { 
            get
            {
                return _baseURL;
            }
        }
    }
}
